<?php

namespace app\api\controller\v2;

use app\api\controller\Common;
use app\api\model\Code;
use app\api\model\VolleyDesc as Balance;
use app\api\model\YaoqingRecords as Income;
use think\Db;
use think\Request;

class Wallet extends Common {
    /**
     * @var mixed
     */
    public $params = null;
    /**
     * @param Request $request
     */
    public function __construct(Request $request = null) {
        parent::__construct($request);
        $this->params = getRsaPostParamArr2();
    }

    /**
     * @return mixed
     */
    public function scoreToVolley() {
        $paypwd = $this->params['paypwd'] ?? '';
        $value  = intval($this->params['value'] ?? 0);

        if ($value <= 0) {
            return $this->miss('操作异常');
        }
        if ($paypwd) {
            if (!$this->member['paypwd']) {
                return $this->miss('尚未设置支付密码');
            }
            if (!password_verify($paypwd, $this->member['paypwd'])) {
                return $this->miss('支付密码错误');
            }
        } else {
            return $this->miss('支付密码错误');
        }

        // $hasTopup = Db::name('user_data')->where(['user_id'=>$this->member['id']])->value('topup');
        // $hasWithdraw = Db::name('withdraw')->where(['userid'=>$this->member['id'], 'state'=>1])->find();
        // if (!$hasTopup && !$hasWithdraw) return $this->miss('当前账号暂不支持兑换');

        $frozen = Db::name('wallet_frozen')->where(['user_id' => $this->member['id']])->find();
        if ($frozen) {
            $this->member['score'] = $this->member['score'] - $frozen['value'];
        }

        if ($this->member['score'] < $value) {
            return $this->miss('账户可用积分不足');
        }

        $result = false;
        Db::startTrans();
        try {
            $state = Income::index($this->member['id'], 0, $value, '积分兑换豆豆', 1, '', 1);
            $beans = $value * 100;
            if ($state) {
                Balance::beans($this->member['id'], $beans, '积分兑换豆豆', 1);
            }
            Db::name('wallet_to_volley')->insert(['user_id'=>$this->member['id'], 'score'=>$value, 'volley'=>$beans, 'time'=>time()]);
            $result = true;
            Db::commit();
        } catch (\Exception $e) {
            $result = false;
            Db::rollback();
        }

        if ($result) {
            return $this->pass('兑换成功');
        }
        return $this->miss('兑换失败,请稍后重试');
    }


    public function bangZfb()
    {
        $userid = $this->member['id'];
        $zhifuname = $this->params['zhifuname'] ?? '';
        $zhifucount = $this->params['zhifucount'] ?? '';
        $code = $this->params['code'] ?? '';

        if (mb_strlen($zhifucount) < 7 || mb_strlen($zhifuname) < 2) {
            return $this->miss('姓名或账号填写错误');
        }

        $verify = Code::verifyCode($this->member['phone'], $code);

        if ($verify['code'] == 400) {
            return $this->miss($verify['msg']);
        }

        $realname = Db::name('user_certification')->where(['types' => 1, 'user_id' => $userid])->value('data2');
        if($realname){
            if ($realname != $zhifuname) {
                return $this->miss('提现账户姓名需与实名信息姓名一致', 201);
            }
        }

        $updateArr = array(
            "zhifuname" => $zhifuname,
            "zhifucount" => $zhifucount
        );
        Db::name('user')->where(['id'=>$userid])->update($updateArr);

        $this->CheckWarn($userid, '绑定支付宝');
        return $this->pass('设置成功');
    }
    private function CheckWarn($user_id, $value)
    {
        $warn = Db::name('user_warn')->find($user_id);
        if($warn){
            Db::name('user_warn_records')->insert(['user_id'=>$user_id, 'desc'=>$value, 'time'=>time()]);
        }else{
            $userinfo = Db::name('user')->find($user_id);
            $userRepeatCheck = Db::name('user_repeat_check')->find($user_id);
            if($userinfo){
                if($userRepeatCheck['zhifucounts']){
                    $zhifucounts = explode(',', $userRepeatCheck['zhifucounts']);
                    if($userinfo['zhifucount']){
                        array_push($zhifucounts, $userinfo['zhifucount']);
                    }
                    $where['u.zhifucount'] = ['in', array_unique($zhifucounts)];
                }elseif($userinfo['zhifucount']){
                    $where['u.zhifucount'] = $userinfo['zhifucount'];
                }
                if($userinfo['phone']){
                    $where['u.zhifucount'] = $userinfo['phone'];
                }
                if($userRepeatCheck['device_ids']){
                    $device_ids = explode(',', $userRepeatCheck['device_ids']);
                    if($userinfo['device_id']){
                        array_push($device_ids, $userinfo['device_id']);
                    }
                    $where['u.device_id'] = ['in', array_unique($device_ids)];
                }elseif($userinfo['device_id']){
                    $where['u.device_id'] = $userinfo['device_id'];
                }
                $warn = Db::name('user_warn')->alias('a')->join('user u','a.user_id=u.id')->whereOr($where)->find();
                if($warn){
                    Db::name('user_warn_records')->insert(['user_id'=>$user_id, 'desc'=>$value . '（来源于用户 '.$warn['id'].'）', 'time'=>time()]);
                }
            }
        }
    }

    public function set_dg_auth()
    {
        $this->member = Db::name('user')->find(11);
        $post = input();
        $post['mobile_no'] = $this->member['phone'];
        $account_info = Db::name('dg_user_account')->where(['user_id'=>$this->member['id']])->find();
        if (!$account_info) {
            try {
                $result = action('api/juhepay/newaccount', ['data'=>$post]);
                $result = $result->getData();
                if ($result['code'] != 200) {
                    return $this->miss($result['msg']);
                }
                $account_info = [
                    'user_id'=>$this->member['id'],
                    'name'=>$post['name'],
                    'cert_no'=>$post['cert_no'],
                    'cert_validity_type'=>$post['cert_validity_type']??0,
                    'cert_begin_date'=>$post['cert_begin_date']??'',
                    'cert_end_date'=>$post['cert_end_date']??'',
                    'mobile_no'=>$post['mobile_no'],
                    'huifu_id'=>$result['data']['data']['huifu_id'],
                    'create_time'=>datetime()
                ];
                $account_info['id'] = Db::name('adapay_user_account')->insertGetId($account_info);
                return $this->pass('设置成功');
            } catch (\Exception $e) {
                return $this->miss('请稍后再试'.$e->getMessage());        
            }
        } else {
            try {
                $post['huifu_id'] = $account_info['huifu_id'];
                $result = action('api/juhepay/editaccount', ['data'=>$post]);
                $result = $result->getData();
                if ($result['code'] != 200) {
                    return $this->miss($result['msg']);
                }
                $update = [
                    'cert_validity_type'=>$post['cert_validity_type']??0,
                    'cert_begin_date'=>$post['cert_begin_date']??'',
                    'cert_end_date'=>$post['cert_end_date']??'',
                    'mobile_no'=>$post['mobile_no'],
                    'update_time'=>datetime()
                ];
                $res = Db::name('adapay_user_account')->where(['id'=>$account_info['id']])->update($update);
                return $this->pass('设置成功');
            } catch (\Exception $e) {
                return $this->miss('请稍后再试'.$e->getMessage());        
            }
        }
    }

    public function set_dg_withdraw()
    {
        $this->member = Db::name('user')->find(11);
        $post = input();
        $account_info = Db::name('dg_user_account')->where(['user_id'=>$this->member['id']])->find();
        $param = [
            'card_type'=>1,
            'card_name'=>$account_info['name'],
            'card_no'=>$post['card_no'],
            'prov_id'=>$post['prov_id'],
            'area_id'=>$post['area_id'],
            'cert_type'=>'00',
            'cert_no'=>$account_info['cert_no'],
            'cert_validity_type'=>$account_info['cert_validity_type'],
            'cert_begin_date'=>$account_info['cert_begin_date'],
            'cert_end_date'=>$account_info['cert_end_date'],
        ];

        try {
            $result = action('api/juhepay/setuserinfo', ['data'=>['card_info'=>$param]]);
            $result = $result->getData();
            if ($result['code'] != 200) {
                return $this->miss($result['msg']);
            }
            $update = [
                'card_no'=>$post['card_no'],
                'prov_id'=>$post['prov_id'],
                'area_id'=>$post['area_id'],
                'update_time'=>datetime()
            ];
            $res = Db::name('dg_user_account')->where(['id'=>$account_info['id']])->update($update);
            return $this->pass('设置成功');
        } catch (\Exception $e) {
            return $this->miss('请稍后再试'.$e->getMessage());        
        }
    }



    public function set_auth()
    {
        // $this->member = Db::name('user')->find(11);
        // $post = input();
        $post = $this->params;
        $post['mobile_no'] = $this->member['phone'];
        $account_info = Db::name('adapay_user_account')->where(['user_id'=>$this->member['id']])->find();
        if (!$account_info) {
            try {
                $result = action('api/adapay/query_user', ['member_id'=>$this->member['id']]);
                $result = $result->getData();
                if ($result['code'] != 200) {
                    return $this->miss($result['msg']);
                }
                $account_info = [
                    'user_id'=>$this->member['id'],
                    'mobile_no'=>$post['mobile_no'],
                    'name'=>$post['name'],
                    'cert_no'=>$post['cert_no'],
                    'card_no'=>$post['card_no'],
                    'huifu_id'=>sizeof($result['data']['settle_accounts'])?$result['data']['settle_accounts'][0]['id']:0,
                    'create_time'=>datetime()
                ];
                $account_info['id'] = Db::name('adapay_user_account')->insertGetId($account_info);
                return $this->pass('设置成功');
            } catch (\Exception $e) {
                return $this->miss('请稍后再试'.$e->getMessage());        
            }
        } else {
            try {
                $result = action('api/adapay/query_user', ['member_id'=>$this->member['id']]);
                $result = $result->getData();
                if ($result['code'] != 200) {
                    return $this->miss($result['msg']);
                }
                $huifu_id = sizeof($result['data']['settle_accounts'])?$result['data']['settle_accounts'][0]['id']:0;
                $update = [
                    'mobile_no'=>$post['mobile_no'],
                    'name'=>$post['name'],
                    'cert_no'=>$post['cert_no'],
                    'card_no'=>$post['card_no'],
                    'huifu_id'=>$huifu_id,
                    'update_time'=>datetime()
                ];
                $res = Db::name('adapay_user_account')->where(['id'=>$account_info['id']])->update($update);
                return $this->pass('设置成功');
            } catch (\Exception $e) {
                return $this->miss('请稍后再试'.$e->getMessage());        
            }
        }
    }
    public function set_withdraw()
    {
        // $this->member = Db::name('user')->find(11);
        // $post = input();
        $post = $this->params;
        $account_info = Db::name('adapay_user_account')->where(['user_id'=>$this->member['id']])->find();
        $param = [
            'card_id' => $post['card_no'],
            'card_name' => $post['name'],
            'cert_id' => $post['cert_no'],
            'cert_type' => '00',
            'tel_no' => $this->member['phone'],
            'bank_acct_type' => 2,
        ];

        try {
            $query_user = action('api/adapay/query_user', ['member_id'=>$this->member['id']]);
            $query_user = $query_user->getData();
            if ($query_user['code'] == 200) {
                $huifu_id = sizeof($query_user['data']['settle_accounts'])?$query_user['data']['settle_accounts'][0]['id']:0;
                if ($huifu_id) {
                    action('api/adapay/delete_settle_account', ['member_id'=>$this->member['id'], 'settle_account_id'=>$huifu_id]);
                }
            }

            $result = action('api/adapay/set_settle_account', ['member_id'=>$this->member['id'], 'account_info'=>$param]);
            $result = $result->getData();
            if ($result['code'] != 200) {
                return $this->miss($result['msg']);
            }
            $this->set_auth();
            return $this->pass('设置成功');
        } catch (\Exception $e) {
            return $this->miss('请稍后再试'.$e->getMessage());        
        }
    }

    public function area_code()
    {
        $areas = Db::name('dg_area_code')->order('id asc')->select();

        $data = [];
        foreach ($areas as $k => $v) {
            $province = $v['province'];
            $city = $v['city'];
            if (!isset($data[$province])) {
                $data[$province] = ['name'=>$v['province'], 'code'=>$v['province_code'], 'child'=>[]];
            }
            if (!isset($data[$province]['child'][$city])) {
                $data[$province]['child'][$city] = ['name'=>$v['city'], 'code'=>$v['city_code'], 'child'=>[]];
            }
            $data[$province]['child'][$city]['child'][] = ['name'=>$v['district'], 'code'=>$v['district_code']];
        }

        foreach ($data as &$value) {
            $value['child'] = array_values($value['child']);
        }
        $data = array_values($data);

        return $this->pass($data);
    }
}